package com.moons.printerdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;

import com.hjq.toast.ToastUtils;
import com.moons.idevices.Devices;
import com.moons.idevices.IPrinter;
import com.moons.idevices.SimpleInitResults;
import com.moons.idevices.model.Appointment;
import com.moons.idevices.model.Visitor;
import com.moons.idevices.utils.PrinterUtils;
import com.moons.idevices.utils.ThreadPool.ThreadPoolManager;
import com.moons.printerdemo.databinding.ActivityMainBinding;

import java.text.SimpleDateFormat;
import java.util.Date;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private final String TAG = this.getClass().getSimpleName();


    private ActivityMainBinding mBinding;
    private UsbBroadCastReceiver mUsbBroadCastReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        mUsbBroadCastReceiver = new UsbBroadCastReceiver();
        registerReceiver(mUsbBroadCastReceiver, intentFilter);

        mBinding.btPrintVisitorAndAppointment.setOnClickListener(view -> {
//            String stateStr = PrinterUtils.getPrinterStatus();
//
//            if (PrinterUtils.isPrintFunctional(stateStr)) {

            Visitor visitor = new Visitor();
            visitor.setName("张三");
            visitor.setCellPhoneNumber("152 3334 4366");
            visitor.setIdCardNumber("3233523444444323333");
            visitor.setType("家长");
            visitor.setHealthCode("绿码");
            visitor.setTemp("36.2°C");

            Appointment appointment = new Appointment();
            appointment.setTips("该凭证当日有效，请妥善保管。");
            appointment.setName("王五");
            appointment.setShangHaiQRCode("绿码");
            appointment.setTemperature("36.6");
//            appointment.setDateAndTime("10月09日 12:00");
            appointment.setWorkOrder("2021 施工队 33333");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            appointment.setDateAndTime(sdf1.format(new Date()));


            appointment.setTempAuthorize(false);

            appointment.setVisitorType("常驻内部人员");

            appointment.setQrcode("234567");
            ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(() -> {

                PrinterUtils.printAppointmentAndVisitor(visitor, appointment);

//                PrinterUtils.printAppointment(appointment,true);

            });

//            } else {
//
//                Toast.makeText(getApplicationContext(), stateStr, Toast.LENGTH_SHORT).show();
//
//            }


        });

        mBinding.btPrintAppointment.setOnClickListener(v -> {


            Appointment appointment = new Appointment();
            appointment.setTips("该凭证当日有效，请妥善保管。");
            appointment.setName("张三一");
            appointment.setShangHaiQRCode("绿码");
            appointment.setTemperature("36.7");
//            appointment.setDateAndTime("10月09日 12:00");
            appointment.setWorkOrder("2021 施工队 22222");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            appointment.setDateAndTime(sdf1.format(new Date()));


            appointment.setTempAuthorize(false);

            appointment.setVisitorType("临时外部人员");

            appointment.setQrcode("123456");
            ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(() -> {


                PrinterUtils.printAppointment(appointment, true);

            });

        });

        mBinding.btTmpAppointment.setOnClickListener(v -> {


            Appointment appointment = new Appointment();
            appointment.setTips("该凭证当日有效，请妥善保管。");
            appointment.setName("张三二");
            appointment.setShangHaiQRCode("绿码");
            appointment.setTemperature("36.5");
//            appointment.setDateAndTime("10月09日 12:00");
//            appointment.setWorkOrder("2021 施工队 11111");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            appointment.setDateAndTime(sdf1.format(new Date()));


            appointment.setTempAuthorize(true);

            appointment.setMatterOfVisit("维护");

            appointment.setTmpAuthorizer("李四");

            appointment.setQrcode("654321");
            ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(() -> {


                PrinterUtils.printAppointment(appointment, true);

            });


        });

        mBinding.btPrintqrcode.setOnClickListener(v -> {


            ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(() -> {


                PrinterUtils.printQRCode("测试二维码：123jhjkdhasdiu", new IPrinter() {
                    @Override
                    public void actionResult(boolean success) {
                        ToastUtils.show("二维码打印结果" + success);
                    }

                    @Override
                    public void onConnected(boolean result) {

                    }
                });

            });


        });

        mBinding.btPrintText.setOnClickListener(v -> {

            ThreadPoolManager.getInstance().getBackgroundExecutorService().execute(() -> {


                PrinterUtils.printerText("测试打印文本：电工撒开了好久的烤辣椒水", new IPrinter() {
                    @Override
                    public void actionResult(boolean success) {
                        ToastUtils.show("文本打印结果" + success);
                    }

                    @Override
                    public void onConnected(boolean result) {

                    }
                });

            });


        });


        Devices.getInstance().deviceInit(this, new SimpleInitResults() {
            @Override
            public void allInitialized(boolean success) {

            }

            @Override
            public void printerConnected(boolean isConnected) {


                if (isConnected) {

                    ToastUtils.show("打印机连接成功");


                } else {

                    ToastUtils.show("打印机连接失败");

                }


            }
        });


    }

    //usb 监听 由于权限问题而且sdk内部有超时时间 ,适用情况应该是系统默认usb权限开放或者root 板则使用UsbNativeApi
    private class UsbBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            switch (intent.getAction()) {
                case UsbManager.ACTION_USB_DEVICE_ATTACHED:
                    // 当USB设备连接到USB总线时，在主机模式下发送此意图。
//                    ToastUtils.show("插入设备 vid:" + device.getVendorId() + "  pid:" + device.getProductId());
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED:
                    // 当USB设备在主机模式下脱离USB总线时发送此意图。
//                    ToastUtils.show("拔出设备 vid:" + device.getVendorId() + "  pid:" + device.getProductId());
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        Devices.getInstance().disconnect();

    }
}